
#include "BidirCir-LinkList.h"


bool LinkListEmpty(PListNode phead)
{
	assert(phead);
	return phead->next == phead;
}

PListNode BuyListNode()
{
	PListNode newNode = (PListNode)malloc(sizeof(ListNode));
	if (newNode == NULL) {
		perror("\nFail to malloc: ");
		return NULL;
	}
	newNode->next = NULL;
	newNode->prev = NULL;
	return newNode;
}

PListNode LinkList_Create()
{
	PListNode phead = BuyListNode();
	if (phead == NULL) {
		printf("\nThere is an error for Buying a phead(NULL) Node!\n");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LinkList_Destroy(PListNode* pphead)
{
	assert(pphead && *pphead);
	PListNode p = (*pphead)->next, q = NULL;
	while (p != *pphead) {
		q = p, p = p->next;
		free(q);
	}
	free(p);
	*pphead = NULL;
}

void LinkListPrint(PListNode phead)
{
	assert(phead);
	int flag = 1;
	PListNode cur = phead;
	while (cur = cur->next, cur != phead) {
		flag = 0;
		printf("%d", cur->val);
		if(cur->next != phead)
			printf(" <-> ");
	}
	if (flag)
		printf("Nothing at all!\n");
	return;
}

void LinkListPushBack(PListNode phead, DataType x)
{
	assert(phead);
	PListNode newNode = BuyListNode();
	if (newNode == NULL) {
		printf("\nThere is an error for Buying a Node(NULL)!\n");
		return;
	}
	newNode->val = x;
	newNode->next = phead;
	newNode->prev = phead->prev;
	phead->prev->next = newNode;
	phead->prev = newNode;
}


void LinkListPopBack(PListNode phead)
{
	assert(phead);
	if (LinkListEmpty(phead)) {
		printf("\nThe LinkList is Empty!\n");
		return;
	}
	PListNode tmp = phead->prev;
	phead->prev = tmp->prev;
	tmp->prev->next = phead;
	free(tmp);
}

void LinkListErase(PListNode pos)
{
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
}

int LinkListSize(PListNode phead)
{
	assert(phead);
	int count = 0;
	PListNode cur = phead;
	while (cur = cur->next, cur != phead)
		++count;
	return count;
}